{                                   
Method:         _LinearRegFaster 

Description:    Replaces TS built-in function LinearRegFC with significantly faster algorithm.

Author:         MarkSanDiego

Updated:        11/03/12    original version


 
Method LinearRegFast notes

  Define inputs and variables in calling program 

    To avoid conflicts with other variables in main program or other Methods, 
    Price, Length and Offset have been renamed LRPrice, LRLength and LROffset.

inputs: 
    LRPrice(Numericseries),         
    LRLength(15);                          { Length must be > 1 }
 
variables: 

    { intrabarpersist required if calculation will occur intrabar, as opposed to only at end of bar }

    Intrabarpersist TgtBar(0),             { use negative integer number for future, positive for past }
    Intrabarpersist oLRSlope(0), 
    Intrabarpersist oLRAngle(0), 
    Intrabarpersist oLRIntercept(0),       { left intercept, at vertical through Price[ Length - 1 ] }
    Intrabarpersist oLRValueRaw(0),
    
    Intrabarpersist LRLength(0),
    Intrabarpersist LROffset(0),
    intrabarpersist LastLRLength(0),
    intrabarpersist LastLROffset(0),
    intrabarpersist double SumXY(0), 
    intrabarpersist double SumY(0), 
    intrabarpersist SumX(0), 
    intrabarpersist SumXSqr(0), 
    intrabarpersist Divisor(0);
}


Method void LinearRegFaster()
    begin
    
        if LRLength > 1 then begin 
            
            If LRLength <> LastLRLength or LROffset <> LastLROffset then begin
            
                SumX = LRLength * (LRLength - 1) * .5; 
                SumXSqr = LRLength * (LRLength - 1) * (2 * LRLength - 1) / 6; 
                Divisor = Square(SumX) - LRLength * SumXSqr;
            
                SumXY = 0;
                for Value1 = 0 to LRLength - 1 begin
                    SumXY = SumXY + Value1 * LRPrice[Value1 + LROffset] ;
                end ;        
                SumY = Summation(LRPrice[LROffset], LRLength);
                
            End else begin
            
                SumY = SumY + LRPrice[LROffset] - LRPrice[LRLength + LROffset];    
                SumXY = SumXY + (SumY - LRPrice[LROffset]) - (LRLength - 1) * LRPrice[LRLength + LROffset];
                
            end;    
            
            oLRSlope = ( LRLength * SumXY - SumX * SumY) / Divisor ;            
            { uncomment if oLRAngle needed }
//            oLRAngle = ArcTangent( oLRSlope );            
            oLRIntercept = ( SumY - oLRSlope * SumX ) / LRLength ;
            oLRValueRaw = oLRIntercept + oLRSlope * ( LRLength - 1 - TgtBar ) ;
            LastLRLength = LRLength;
            LastLROffset = LROffset;
            
        end;
        
    end;